package com.wx.mythread.stopthread.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * volatile的局限性，在阻塞中无法正常的停止线程
 * 举例：生产者和消费者的案例中，生产者生产的很快，消费者消费的很慢
 * 因为线程陷入了阻塞，
 */
public class WrongWayVolatileCantStop {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new ArrayBlockingQueue(10);

        Producer producer = new Producer(blockingQueue);
        Thread thread = new Thread(producer);
        thread.start();
        Thread.sleep(1000);

        Consumer consumer = new Consumer(blockingQueue);
        while (consumer.needMoreNums()) {
            System.out.println(blockingQueue.take() + "被消费了");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要更多的数据了");
        producer.canceled  = true;
        System.out.println(producer.canceled);

    }
}

class Producer implements Runnable{

    private BlockingQueue storage;

    public volatile boolean canceled = false;

    public Producer(BlockingQueue storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        int num = 0;
        try {
            while (num < 100000 && !canceled){
                if (num % 100 == 0){
                    //put操作慢的时候，线程会阻塞
                    storage.put(num);
                    System.out.println(num + "是100的倍数，放到仓库中");
                }
                num++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生成者停止运行");
        }
    }
}

class Consumer{
    private BlockingQueue storage;

    public Consumer(BlockingQueue storage) {
        this.storage = storage;
    }

    public boolean needMoreNums(){
        if (Math.random() > 0.95){
            return false;
        }
        return true;
    }
}
